import ProductModel from "../../../models/Product";
import ImageModel from "../../../models/Image";
import Crypt from "../../../utils/Crypt";
import UserModel from "../../../models/User";
import config from "../../../config/config";
import CartModel from "../../../models/Cart";

const productModel = new ProductModel()
const imageModel = new ImageModel()
const userModel = new UserModel()
const cartModel = new CartModel()

Page({
  data: {
    product: {},
    image: {},
    // group id
    group: -1,
    // sku
    haveSku: false,
    // pop
    showPop: false,
    popType: 0,
    id: -1,
    product_qrcode: ''
  },
  onLoad: function (options) {
    this.setData({ id: options.id })

    // product
    productModel.getDetail({ id: options.id }).then(response => {
      let { data } = response
      data = Crypt.parse(data)

      // data.inText = data.inText.replace(/<[^>]+>/g, '')

      this.setData({ product: data })

      // have sku
      const result = data.sku && data.sku.length > 0 && data.skuName && data.skuName.length > 0
      this.setData({ haveSku: result })

      // share
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline'],
        success: () => {
          // console.log('ok')
          // 可以把分享记录保存到数据库
        }
      })
    })

    // image
    imageModel.getRemoteImage().then(data => {
      this.setData({ image: data.detail })
    })


    // is group (group id)
    if (options.group && +options.group > 0) {
      this.setData({ group: options.group })
    }

  },

  changeProduct(e) {
    const product = e.detail.product
    this.setData({ product })
  },

  openPop(e) {
    const type = e.detail.type
    this.setData({
      popType: type,
      showPop: true
    })
  },

  closePop() {
    this.setData({
      showPop: false
    })
  },

  _getOptions(e) {
    if (!e.detail) {
      return {
        price: this.data.product.price,
        product_id: this.data.id,
        quantity: 1
      }
    } else {
      return {
        ...e.detail,
        product_id: this.data.id
      }
    }
  },

  addCart(e) {
    userModel.addCart({ ...this._getOptions(e) }).then(() => {
      wx.showToast({
        title: '添加成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/cart/index'
            })
          }, 600)
        }
      })
    })
  },

  buy(e) {
    cartModel.checkRepeat({ id: this.data.id }).then(() => {
      const params = this._getOptions(e)
      wx.navigateTo({
        url: '/sub_main/pages/order/index?params=' + JSON.stringify(params)
      })
    })
  },

  createGroup(e) {
    const params = {
      ...this._getOptions(e),
      create_group: true
    }
    wx.navigateTo({
      url: '/sub_main/pages/order/index?params=' + JSON.stringify(params)
    })
  },

  joinGroup(e) {
    const params = {
      ...this._getOptions(e),
      group_id: this.data.group
    }
    wx.navigateTo({
      url: '/sub_main/pages/order/index?params=' + JSON.stringify(params)
    })
  },

  randomGroup(e) {
    const params = {
      ...this._getOptions(e),
      random_group: true
    }
    wx.navigateTo({
      url: '/sub_main/pages/order/index?params=' + JSON.stringify(params)
    })
  },

  // 产品二维码
  handleQrcode(e) {
    const product = this.data.product
    userModel.qrcodeShare({
      id: product.id
    }).then(response => {
      const { data } = response
      const url = config.app_base_url + data.path
      this.setData({
        product_qrcode: url
      })
    })
  },

  downQrcode() {
    wx.downloadFile({
      url: this.data.product_qrcode,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '保存成功',
                success: () => {
                }
              })
            }
          })
        }
      },
      complete: () => {
        this.setData({
          product_qrcode: ''
        })
      }
    })
  }

});
